const inputNumber = {
  bind: function(el, binding, vnode, oldVnode) {
    const arg = binding.arg || ''
    const modifiers = binding.modifiers || {}
    const value = binding.value
    el.validateNum = function(e) {
      if (arg === 'float' || modifiers.float) {
        if (!/^(\d+\.\d+)$|^(\d+)$/.test(e.target.value)) {
          e.target.value = 0
          vnode.componentInstance.$emit('input', 0)
          vnode.componentInstance.$emit('change', 0)
        } else if (value) {
          e.target.value = parseFloat(e.target.value).toFixed(value)
        }
      } else {
        if (!/^(\d+)$/.test(e.target.value)) {
          e.target.value = 0
        }
      }
    }
    el.addEventListener('change', el.validateNum)
  },
  unbind(el, binding, vnode, oldVnode) {
    el.removeEventListener('change', el.validateNum)
    el.validateNum = undefined
  }
}

export default {
  install(Vue) {
    Vue.directive('number', inputNumber)
  }
}
